import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:provider/provider.dart';

import '../model/message_preview.dart';
import '../provider/AuthProvider.dart';
import '../utils/api.dart';
import 'chat_page.dart';

class MessagePage extends StatefulWidget {
  const MessagePage({super.key});

  @override
  State<MessagePage> createState() => _MessagePageState();
}

class _MessagePageState extends State<MessagePage> {
  List<MessagePreview> previews = [];
  bool _loading = true;

  @override
  void initState() {
    super.initState();
    _loadPreviews();
  }

  Future<void> _loadPreviews() async {
    final myId = context.read<AuthProvider>().userId;
    if (myId == null) return;

    try {
      final res = await Api.get(
        '/message/conversations',
        params: {'userId': myId},
      );
      final list = List<Map<String, dynamic>>.from(res['data']);
      final items = list.map((e) => MessagePreview.fromJson(e, myId)).toList();

      setState(() {
        previews = items;
        _loading = false;
      });
    } catch (e) {
      print("加载消息失败: $e");
      setState(() => _loading = false);
    }
  }

  @override
  Widget build(BuildContext context) {
    final myId = context.read<AuthProvider>().userId!;
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(title: const Text('消息')),
      body: _loading
          ? const Center(child: CircularProgressIndicator())
          : ListView.builder(
              itemCount: previews.length,
              itemBuilder: (context, index) {
                final preview = previews[index];
                final msg = preview.lastMessage;
                return ListTile(
                  leading: CircleAvatar(
                    backgroundImage: NetworkImage(preview.avatar),
                    radius: 24,
                  ),
                  title: Text(preview.nickname),
                  subtitle: Text(
                    msg.content,
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                  ),
                  trailing: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Text(
                        formatTime(msg.timestamp),
                        style: const TextStyle(fontSize: 12),
                      ),
                      if (preview.unreadCount > 0)
                        Container(
                          margin: const EdgeInsets.only(top: 4),
                          padding: const EdgeInsets.all(4),
                          decoration: const BoxDecoration(
                            color: Colors.red,
                            shape: BoxShape.circle,
                          ),
                          child: Text(
                            '${preview.unreadCount}',
                            style: const TextStyle(
                              fontSize: 10,
                              color: Colors.white,
                            ),
                          ),
                        ),
                    ],
                  ),
                  onTap: () {
                    Navigator.push(
                      context,
                      MaterialPageRoute(
                        builder: (_) => ChatPage(
                          nickname: preview.nickname,
                          userId: preview.userId,
                          myId: myId,
                        ),
                      ),
                    );
                  },
                );
              },
            ),
    );
  }

  String formatTime(DateTime time) {
    final now = DateTime.now();
    final diff = now.difference(time);
    if (diff.inMinutes < 60) {
      return '${diff.inMinutes} 分钟前';
    } else if (diff.inHours < 24) {
      return '${diff.inHours} 小时前';
    } else {
      return DateFormat('MM/dd HH:mm').format(time);
    }
  }
}
